
package com.treeman.navi.login;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.treeman.navi.rest.RestClient;
import com.treeman.navi.rest.RestClient.HttpConnectionStatus;
import com.treeman.navi.rest.RestClient.RequestMethod;


public class WrongAccesTokenException extends Exception
{

    private static String TAG = "WrongAccesTokenException";

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    public WrongAccesTokenException(final RestClient thrownClient)
    {
	Looper.prepare();
	Session.setSessionStatus(false);

	Handler handler = new Handler()
	{

	    @Override
	    public void handleMessage(Message msg)
	    {
		if (msg.what == HttpConnectionStatus.START.ordinal())
		{
		    Log.i(TAG, "Starting connection for resign... ");

		}
		if (msg.what == HttpConnectionStatus.SUCCESS.ordinal())
		{
		    Log.i(TAG, "Connection success! Resigning");

		    try
		    {
			RestClient restClient = (RestClient) msg.obj;

			String response = restClient.getResponse();

			Log.i(TAG, "Response: " + response + "( RESPONSE CODE " + restClient.getResponseCode() + ")");
			Session.setSessionStatus(true);
			Session.setAccess_token(response);

			Log.i(TAG, "Looper thread: " + Looper.myLooper().getThread().getName());

			Looper.myLooper().quit();

		    }
		    catch (Exception ex)
		    {
			Log.e(TAG, " SUCCESS error : ", ex);
		    }
		}
		if (msg.what == HttpConnectionStatus.ERROR.ordinal())
		{
		    try
		    {

			ApiRequestError apiRequestError = (ApiRequestError) msg.obj;
			Log.i(TAG, "Response: " + apiRequestError.getReason() + " -- PROBABLY YOU NEED TO QUIT APP AND LOGIN AGAIN");

		    }
		    catch (Exception ex)
		    {
			Log.e(TAG, " CONNECTION error : ", ex);
		    }

		}
	    }
	};

	RestClient restClient = new RestClient(Session.getAddress() + "/api/login", handler);
	try
	{

	    restClient.addParam("username", Session.getUsername());
	    restClient.addParam("password", Session.getPassword());

	    restClient.addHeader("Accept", "application/json");

	    restClient.execute(RequestMethod.POST);

	    Looper.loop();

	}
	catch (Exception ex)
	{
	    Log.e(TAG, " RestClient error : ", ex);

	}
    }

}
